package com.fitness.club.util;

import com.fitness.club.model.DatabaseConfig;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.core.ParseException;
import freemarker.template.*;

import java.com.fitness.club.model.TableInfo;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Freemarker工具类
 * 
 * @author afan
 *
 */
public class FreemarkerUtil {

	private Configuration cfg = null;

	private String encoding = "UTF-8";

	public FreemarkerUtil() throws UnsupportedEncodingException, IOException {
		super();
		this.initConfiguration();
	}

	private void initConfiguration() throws UnsupportedEncodingException, IOException {
		cfg = new Configuration(Configuration.VERSION_2_3_21);
		ClassTemplateLoader ctl1 = new ClassTemplateLoader(getClass(), "");
		FileTemplateLoader ftl = new FileTemplateLoader(new File(this.getClassPath()));
		TemplateLoader[] loaders = new TemplateLoader[] { ctl1,ftl };
		MultiTemplateLoader mtl1 = new MultiTemplateLoader(loaders);
		cfg.setTemplateLoader(mtl1);
		cfg.setDefaultEncoding(encoding);
		cfg.setOutputEncoding(encoding);
	}

	/**
	 * 
	 * 
	 * @param table
	 * @param tempname
	 * @param filepath
	 * @param databaseConfig
	 * @throws IOException
	 * @throws ParseException
	 * @throws MalformedTemplateNameException
	 * @throws TemplateNotFoundException
	 * @throws TemplateException 
	 */
	public void createFileByTempalte(TableInfo table, String tempname, String filepath, DatabaseConfig databaseConfig)
			throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
		Template template = cfg.getTemplate(tempname, encoding);
		File descFile=new File(filepath);
		if (!descFile.getParentFile().exists() || !descFile.getParentFile().isDirectory()) {
			descFile.getParentFile().mkdirs();
		}
		FileWriter out=new FileWriter(descFile);
		Map<String,Object> datas=new HashMap<String,Object>();
		datas.put("tableinfo", table);
		datas.put("config", databaseConfig);
		template.process(datas, out);
	}


	private String getClassPath() throws UnsupportedEncodingException{
		String classpath=URLDecoder.decode(Thread.currentThread().getContextClassLoader().getResource("").getPath(),"UTF-8");
		return new File(classpath).getAbsolutePath();
	}
}
